package top.ligongzi.hrm.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//Fiegn拦截器
@Component //交给Spirng管理
@Slf4j
public class DefaultOAuth2FeignRequestInterceptor implements RequestInterceptor {

    private static  final String AUTHORIZATION = "Authorization";

    //底层ribbon发送http请求所需要模版
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //从请求头中获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                    requestAttributes;

            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader(AUTHORIZATION);
            if (StringUtils.hasLength(token)){
                log.info("token----->"+token);
                //通过requestTemplate设置token到下一个微服务
                requestTemplate.header("Authorization",token);
            }else {
                log.error("Get request error!");
            }
        }else{
            log.error("Get request error!");
        }
    }
}